<template>
	<view>
		<image class="login-bg"
			src="https://7463-tcb-aon0buztmuvnaubaafe5d-f16fd4-1305412960.tcb.qcloud.la/village/loginbg.jpg"></image>
		<view class="loginline"></view>
		<view class="login-main">
			<u-image class="logintx" :src="imgUrl" shape="circle" width="150" height="150"></u-image>
			<view class="title">{{info.name}}</view>
			<view class="input-box input-boxa">
				<view class="boxa">
					<u-form :model="form" :rules="rules" ref="uForm" :errorType="errorType">
						<u-form-item class="boxinput" prop="code">
							<image class="icon"
								src="https://7463-tcb-aon0buztmuvnaubaafe5d-f16fd4-1305412960.tcb.qcloud.la/village/inputicona.png">
							</image>
							<u-input v-model="phoneNo" placeholder="请输入手机号" tupe="text"
								placeholder-style="color:#999;" :border="border"></u-input>
							<view slot="right">
								<u-button shape="square" type="error" size="mini" :border="border"
									:custom-style="customStyle" v-if="!logged" open-type="getUserInfo"
									@getuserinfo="mpWxLogin">微信授权</u-button>
							</view>
							<view slot="right">
								<u-button shape="square" type="error" size="mini" :border="border"
									:custom-style="customStyle" v-if="logged" open-type="getPhoneNumber"
									@getphonenumber="getPhoneNumber">获取手机号</u-button>
							</view>
						</u-form-item>
					</u-form>
				</view>
			</view>
			<view class="btn-box">
				<u-button :custom-style="uploginStyle" shape="circle" @click="uplogin">
					登录
				</u-button>
			</view>
			<view  class="btn-boxa" v-if="phoneFlag">
				<u-button hover-class="none" type="error"  :border="border" class="icon" :custom-style="customStyle2" @click="upwxlogin">
				</u-button>
				<text>微信一键登录</text>
			</view>
		</view>

	</view>
</template>

<script>
import {
  Login,
  oneKeyLogin,
  postWxUserInfo,
} from "/common/api/register.js";
// import { mpWxGetSessionKey, mpWxGetPhoneNo } from "/src/util/wxauth";
import { mpWxGetPhoneNo } from "/src/util/wxauth";
let that

export default {
  data() {
    return {
      sessionId: uni.getStorageSync("sessionId"),
      imgUrl:
        "https://7463-tcb-aon0buztmuvnaubaafe5d-f16fd4-1305412960.tcb.qcloud.la/village/wxupicon.png",
      info: {},
      customStyle2: {
        background:
          "url('https://7463-tcb-aon0buztmuvnaubaafe5d-f16fd4-1305412960.tcb.qcloud.la/village/wxupicon.png') no-repeat center",
      },
      customStyle: {
        background: "#2dca96",
        color: "#fff",
        fontSize: "26rpx",
        padding: "30rpx 25rpx",
      },
      uploginStyle: {
        background: "#2dca96",
        color: "#fff",
      },
      passwordIcon: true,
      border: false,
      errorType: ["message"],
      phoneNo: "",
      phoneFlag: false,
      logged: false,
      rules: {
        name: [
          {
            required: true,
            message: "请输入手机号",
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },
  onLoad() {
    that = this
    if (uni.getStorageSync('_phone')) {
      that.phoneFlag = true
    }
  },
  computed: {},
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  methods: {
    handleOneKeyLogin(data) {
      oneKeyLogin(data).then((res) => {
        // console.log('debug---------2',res);
        uni.setStorageSync("_accessToken", res.admin_token);
        uni.showToast({
          title: "登录成功",
          icon: 'none',
          duration: 1000
        })
        setTimeout(() => {
          that.phoneNo = ''
          that.$Router.push({
            name: "home",
          });
        }, 1000);
      });
    },
    async mpWxLogin(userInfoData) {
				// console.log("登陆")
				await this.mpWxGetUserInfo(userInfoData)
				uni.showToast({
					title: "请点击获取手机号",
					icon: 'none',
					duration: 1000
				})
				this.logged = true;
			},
    //获取手机号码
			async getPhoneNumber(e) {
				// console.log("getPhoneNumber", e)
				const _userInfo = await uni.getStorageSync('_userInfo')
				const res = await mpWxGetPhoneNo({
					sessionKey: _userInfo.session_key,
					encryptedData: e.detail.encryptedData,
					iv: e.detail.iv
				});
				// console.log("getPhoneNumber------", res)
        await uni.setStorageSync('_phone', res.userInfo.phoneNumber)
				this.phoneNo = res.userInfo.phoneNumber
			},
    // 获取用户信息
    async mpWxGetUserInfo(userInfoData) {
      // console.log('mpWxGetUserInfo---', userInfoData)
      if (!userInfoData.detail.userInfo) {
        uni.showToast({
					title: "未获取到用户信息！",
					icon: 'error',
					duration: 1000
				})
        return;
      }
      const [loginErr, loginData] = await uni.login({
        provider: "weixin",
      });
      const [err, userData] = await uni.getUserInfo();
      const Data = {
        js_code: loginData.code,
        encryptedData: encodeURIComponent(userData.encryptedData),
        iv: userData.iv,
      };
      // 下面那行不能用，微信禁止前端调用
      // const {session_key, userInfo} = await mpWxGetSessionKey(Data);
      const res = await Login(Data)
      uni.setStorageSync("_userInfo", res)
    },
     uplogin() {
				if (!this.logged) {
					uni.showToast({
						title: "请先点击微信授权",
						icon: 'none',
						duration: 1000
					})
				} else if (this.phoneNo === "") {
					uni.showToast({
						title: "请点击获取手机号",
						icon: 'none',
						duration: 1000
					})
				} else {
					this.getAuth()
				}
     },
    async getAuth() {
      const _phone = uni.getStorageSync('_phone');
      const _userInfo = uni.getStorageSync('_userInfo');
      const res = await postWxUserInfo({ phone: _phone, userInfo: _userInfo})
      // console.log('res_phone11111', res)
      if (res) {
        // console.log('res_phone22222', res)
        uni.setStorageSync('_userInfo', res)
        that.handleOneKeyLogin({openId: res.openId})
      }
    },
    upwxlogin() {
      /*try {
        let _userInfo = uni.getStorageSync("_userInfo");
        if (_userInfo) {
          that.handleOneKeyLogin({openId: _userInfo.openId})
        }
      } catch (error) {}*/
      this.getAuth()
    },
  },
};
</script>

<style>
.login-bg {
  position: fixed;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  z-index: -1;
}
.loginline {
  width: 95%;
  margin: 0 auto;
  height: 2rpx;
  background: #f1f1f1;
  display: block;
}
.login-main {
  width: 90%;
  margin: 0 auto;
  padding-top: 60rpx;
}
.login-main .logintx {
  width: 180rpx;
  height: 180rpx;
  border-radius: 50%;
  display: block;
  margin: 0 auto;
}
.login-main .title {
  text-align: center;
  padding-top: 26rpx;
  font-size: 36rpx;
  color: #666;
  font-family: 微软雅黑;
}
.login-main .input-box {
  width: 100%;
  padding: 60rpx 3% 0;
}
.login-main .input-boxa {
  padding-top: 110rpx;
}
.login-main .input-box .boxinput {
  padding: 22rpx 0;
}
.login-main .input-box .boxinput .u-form-item--right__content__slot {
  display: flex;
  align-items: center;
}
.login-main .input-box .boxinput .icon {
  width: 45rpx;
  height: 45rpx;
  display: block;
  padding-right: 15rpx;
}
.login-main .btn-box {
  width: 75%;
  margin: 0 auto;
  padding-top: 150rpx;
}
.login-main .btn-boxa {
  padding-top: 65rpx;
}
.login-main .btn-boxa .icon {
  width: 95rpx;
  height: 95rpx;
  display: block;
  margin: 0 auto;
}
.login-main .btn-boxa text {
  text-align: center;
  color: #b5b5b5;
  display: block;
  padding-top: 30rpx;
}
</style>
